import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/store'

const token = store.getters.getToken

// create an axios instance
const service = axios.create({
  // baseURL: 'http://81.68.131.6:8130',
  baseURL: 'http://localhost:8130',
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (token) {
      config.headers['token'] = token
    }
    return config
  },

  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 20000) {
      return response.data
    } else {
      return Promise.reject('error')
    }
  },

  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
